"""
PDF preview widget with thumbnails and page view.
"""

from typing import List, Optional
import logging

from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QScrollArea,
    QListWidget, QListWidgetItem, QLabel, QFrame,
    QPushButton, QSizePolicy, QAbstractItemView, QSplitter
)
from PyQt6.QtCore import Qt, pyqtSignal, QSize, QThread, QTimer, QItemSelectionModel
from PyQt6.QtGui import QPixmap, QPainter, QPen, QColor, QIcon

from ..core.pdf_processor import PDFProcessor
from ..i18n import tr


class ThumbnailListWidget(QListWidget):
    """Custom list widget for thumbnails."""

    def __init__(self):
        super().__init__()
        # Use ListMode instead of IconMode to avoid icon display area
        self.setViewMode(QListWidget.ViewMode.ListMode)
        self.setResizeMode(QListWidget.ResizeMode.Adjust)
        self.setMovement(QListWidget.Movement.Static)
        self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
        self.setSpacing(2)  # Reduced spacing for list mode
        self.setUniformItemSizes(True)

        # 设置样式表以确保选中状态正确显示
        self.setStyleSheet("""
            QListWidget {
                background-color: white;
                outline: none;
                font-size: 12px;
            }
            QListWidget::item {
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                padding: 8px 12px;
                margin: 2px;
                background-color: #f8f8f8;
                min-height: 20px;
            }
            QListWidget::item:hover {
                border-color: #4CAF50;
                background-color: #f0f8f0;
            }
            QListWidget::item:selected {
                border-color: #2196F3;
                background-color: #e3f2fd;
                font-weight: bold;
                color: #1976D2;
            }
            QListWidget::item:selected:!active {
                border-color: #2196F3;
                background-color: #e3f2fd;
            }
        """)


class PageViewWidget(QScrollArea):
    """Widget for displaying full page preview."""

    def __init__(self):
        super().__init__()
        self.page_label = QLabel()
        self.page_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.page_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        # 添加样式并启用高质量缩放
        self.page_label.setStyleSheet("""
            QLabel {
                background-color: #f0f0f0;
                border: 1px solid #ccc;
            }
            QLabel {
                image-rendering: high-quality;
            }
        """)

        self.setWidget(self.page_label)
        self.setWidgetResizable(True)
        self.setMinimumWidth(300)

        self.current_page: int = -1
        self.zoom_factor: float = 1.0
        self.current_pixmap: Optional[QPixmap] = None

    def display_page(self, pixmap: QPixmap):
        """Display a page pixmap."""
        self.current_pixmap = pixmap

        if pixmap.isNull():
            self.page_label.setText(tr("No preview available"))
            return

        # Apply zoom
        if self.zoom_factor != 1.0:
            size = pixmap.size()
            scaled_size = size * self.zoom_factor
            scaled_pixmap = pixmap.scaled(
                scaled_size,
                Qt.AspectRatioMode.KeepAspectRatio,
                Qt.TransformationMode.SmoothTransformation
            )
            self.page_label.setPixmap(scaled_pixmap)
        else:
            self.page_label.setPixmap(pixmap)

    def set_zoom(self, factor: float):
        """Set zoom factor."""
        self.zoom_factor = factor
        if self.current_pixmap:
            self.display_page(self.current_pixmap)

    def clear(self):
        """Clear the page view."""
        self.page_label.clear()
        self.current_pixmap = None
        self.current_page = -1


class PreviewWidget(QWidget):
    """PDF preview widget with thumbnails and page view."""

    # Signals
    page_selected = pyqtSignal(int)  # Page index
    selection_changed = pyqtSignal(list)  # List of selected page indices

    def __init__(self):
        super().__init__()
        self.pdf_processor: Optional[PDFProcessor] = None
        self.selected_pages: List[int] = []
        self.logger = logging.getLogger(__name__)

        self.init_ui()

    def init_ui(self):
        """Initialize the user interface."""
        # Main layout
        layout = QVBoxLayout(self)
        layout.setContentsMargins(5, 5, 5, 5)

        # Header with controls
        header_layout = QHBoxLayout()

        self.page_label = QLabel(tr("No document loaded"))
        self.page_label.setStyleSheet("font-weight: bold;")
        header_layout.addWidget(self.page_label)

        header_layout.addStretch()

        # Zoom controls
        self.zoom_in_btn = QPushButton("+")
        self.zoom_in_btn.setMaximumWidth(30)
        self.zoom_in_btn.clicked.connect(self.zoom_in)
        header_layout.addWidget(self.zoom_in_btn)

        self.zoom_out_btn = QPushButton("-")
        self.zoom_out_btn.setMaximumWidth(30)
        self.zoom_out_btn.clicked.connect(self.zoom_out)
        header_layout.addWidget(self.zoom_out_btn)

        self.reset_zoom_btn = QPushButton("100%")
        self.reset_zoom_btn.setMaximumWidth(50)
        self.reset_zoom_btn.clicked.connect(self.reset_zoom)
        header_layout.addWidget(self.reset_zoom_btn)

        self.fit_window_btn = QPushButton(tr("Fit"))
        self.fit_window_btn.setMaximumWidth(40)
        self.fit_window_btn.clicked.connect(self.fit_to_window)
        header_layout.addWidget(self.fit_window_btn)

        layout.addLayout(header_layout)

        # Splitter for thumbnails and page view
        self.splitter = QSplitter(Qt.Orientation.Horizontal)

        # Thumbnail list
        self.thumbnail_list = ThumbnailListWidget()
        self.thumbnail_list.itemClicked.connect(self.on_thumbnail_clicked)
        self.thumbnail_list.itemSelectionChanged.connect(self.on_selection_changed)

        # Page view
        self.page_view = PageViewWidget()

        # Add to splitter
        self.splitter.addWidget(self.thumbnail_list)
        self.splitter.addWidget(self.page_view)
        self.splitter.setStretchFactor(0, 1)
        self.splitter.setStretchFactor(1, 2)

        # Set initial sizes (30% for thumbnails, 70% for page view)
        self.splitter.setSizes([300, 700])

        layout.addWidget(self.splitter)

    def load_document(self, processor: PDFProcessor):
        """Load a PDF document for preview."""
        self.pdf_processor = processor

        if not processor.is_loaded():
            self.clear()
            return

        # Clear current content
        self.thumbnail_list.clear()
        self.page_view.clear()

        # Update page count
        page_count = processor.get_page_count()
        self.page_label.setText(tr("%1 pages", page_count))

        # Load thumbnails
        self.load_thumbnails()

        # Auto-display first page preview
        if page_count > 0:
            self.display_page(0)

    def load_thumbnails(self):
        """Load page thumbnails with zero preloading - only load on demand."""
        if not self.pdf_processor:
            return

        page_count = self.pdf_processor.get_page_count()

        # Create placeholder items with text only (no rendering)
        for i in range(page_count):
            item = QListWidgetItem()
            item.setText(tr("Page %1", i + 1))
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            item.setData(Qt.ItemDataRole.UserRole, i)
            # Note: NO icon() call - no rendering yet
            self.thumbnail_list.addItem(item)

    
    def display_page(self, page_index: int):
        """Display a specific page."""
        if not self.pdf_processor or page_index < 0:
            return

        page_count = self.pdf_processor.get_page_count()
        if page_index >= page_count:
            return

        # Get page preview with appropriate resolution
        preview_size = QSize(800, 1066)  # 恢复较高的分辨率用于预览
        pixmap = self.pdf_processor.render_page_thumbnail(page_index, (preview_size.width(), preview_size.height()))

        if pixmap and not pixmap.isNull():
            self.page_view.display_page(pixmap)
        else:
            # If preview fails, show a placeholder
            self.page_view.page_label.setText(tr("Page %1\n(Preview not available)", page_index + 1))
            self.page_view.page_label.setStyleSheet("""
                QLabel {
                    background-color: #f0f0f0;
                    border: 2px dashed #ccc;
                    padding: 20px;
                    font-size: 16px;
                    color: #666;
                }
            """)

        # Update selection
        self.select_page(page_index)

        # Emit signal
        self.page_selected.emit(page_index)

    def select_page(self, page_index: int):
        """Select a specific page in the thumbnail list."""
        # Block signals to prevent double updates
        self.thumbnail_list.blockSignals(True)

        try:
            # Clear all selections first
            self.thumbnail_list.setCurrentItem(None, QItemSelectionModel.SelectionFlag.NoUpdate)
            self.thumbnail_list.clearSelection()

            # Find and select the target item
            for i in range(self.thumbnail_list.count()):
                item = self.thumbnail_list.item(i)
                if item and item.data(Qt.ItemDataRole.UserRole) == page_index:
                    # Set this item as selected
                    item.setSelected(True)
                    self.thumbnail_list.setCurrentItem(item)
                    self.thumbnail_list.scrollToItem(item)
                    break
        finally:
            # Re-enable signals
            self.thumbnail_list.blockSignals(False)

    def get_selected_pages(self) -> List[int]:
        """Get list of selected page indices."""
        selected_items = self.thumbnail_list.selectedItems()
        pages = []
        for item in selected_items:
            page_index = item.data(Qt.ItemDataRole.UserRole)
            if page_index is not None:
                pages.append(page_index)
        return sorted(pages)

    def select_all_pages(self):
        """Select all pages."""
        self.thumbnail_list.selectAll()
        self.on_selection_changed()

    def deselect_all_pages(self):
        """Deselect all pages."""
        self.thumbnail_list.clearSelection()
        self.on_selection_changed()

    def zoom_in(self):
        """Zoom in the page view."""
        current_zoom = self.page_view.zoom_factor
        new_zoom = min(current_zoom * 1.2, 5.0)  # Max 5x zoom
        self.page_view.set_zoom(new_zoom)

    def zoom_out(self):
        """Zoom out the page view."""
        current_zoom = self.page_view.zoom_factor
        new_zoom = max(current_zoom / 1.2, 0.1)  # Min 0.1x zoom
        self.page_view.set_zoom(new_zoom)

    def reset_zoom(self):
        """Reset zoom to 100%."""
        self.page_view.set_zoom(1.0)

    def fit_to_window(self):
        """Fit page to window size."""
        if not self.page_view.current_pixmap:
            return

        # Calculate zoom factor to fit to window
        widget_size = self.page_view.viewport().size()
        pixmap_size = self.page_view.current_pixmap.size()

        # Calculate scale factors
        scale_x = (widget_size.width() - 20) / pixmap_size.width()  # 20px margin
        scale_y = (widget_size.height() - 20) / pixmap_size.height()  # 20px margin

        # Use the smaller scale to fit entire image
        fit_scale = min(scale_x, scale_y, 2.0)  # Max 2x zoom

        self.page_view.set_zoom(fit_scale)

  
    def on_thumbnail_clicked(self, item: QListWidgetItem):
        """Handle thumbnail click - display page preview without loading icon."""
        page_index = item.data(Qt.ItemDataRole.UserRole)
        if page_index is not None:
            # Don't load thumbnail icon, just display page preview
            # self.load_thumbnail_on_demand(page_index)  # Commented out to prevent icon loading

            # Display page preview in the right panel
            self.display_page(page_index)

            # Emit the page selected signal
            self.page_selected.emit(page_index)

    def on_selection_changed(self):
        """Handle selection change."""
        self.selected_pages = self.get_selected_pages()
        self.selection_changed.emit(self.selected_pages)

    def clear(self):
        """Clear all content."""
        self.thumbnail_list.clear()
        self.page_view.clear()
        self.page_label.setText("No document loaded")
        self.selected_pages.clear()
        self.pdf_processor = None